/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */

package com.android.music.util;

import java.text.Collator;
import java.util.ArrayList;
import java.util.List;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.android.music.R;
import com.android.music.model.Music;

/**
 * music 增删查改
 * 
 * @author LeiKang
 */
public class MusicOperate {

    public static String[] mCursorCols = new String[] {
            "audio._id AS _id", MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ALBUM_ID,
            MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION
    };

    Uri MUSIC_URL = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

    /**
     * 获取所有歌曲数据,未排序
     * 
     * @param context
     * @return
     */
    public List<Music> getAllMusic(Context context) {

        List<Music> mListMusic = new ArrayList<Music>();
        Cursor cursor = context.getContentResolver().query(MUSIC_URL, mCursorCols, Util.TIME_WHERE,
                null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {
                mListMusic.add(cursorToMusic(cursor, context));
                cursor.moveToNext();
            }
        }
        return mListMusic;
    }

    /**
     * cursor转化为music
     * 
     * @param cursor
     * @return
     */
    public Music cursorToMusic(Cursor cursor, Context context) {
        Music music = new Music();

        music.id = cursor.getInt(0);
        music.artist = cursor.getString(1);
        music.album = cursor.getString(2);
        music.title = cursor.getString(3);
        music.path = cursor.getString(4);
        music.mimeType = cursor.getString(5);
        music.albumId = cursor.getInt(6);
        music.artistId = cursor.getInt(7);
        music.duration = toTime(cursor.getInt(8));
        music.totalTime = cursor.getInt(8);
        if (cursor.getString(1).equals("<unknown>"))
            music.artist = context.getString(R.string.unknown_artist_name);
        return music;
    }

    /**
     * 播放秒数转化为时分
     * 
     * @param time
     * @return
     */
    public static String toTime(int time) {
        time /= 1000;
        int minute = time / 60;
        int second = time % 60;
        minute %= 60;
        return String.format("%02d:%02d", minute, second);
    }

    public Cursor getArtistCursor(Context context, AsyncQueryHandler async, String filter) {

        StringBuilder where = new StringBuilder();
        where.append(MediaStore.Audio.Artists.ARTIST + " != ''");

        // Add in the filtering constraints
        String[] keywords = null;
        if (filter != null) {
            String[] searchWords = filter.split(" ");
            keywords = new String[searchWords.length];
            Collator col = Collator.getInstance();
            col.setStrength(Collator.PRIMARY);
            for (int i = 0; i < searchWords.length; i++) {
                String key = MediaStore.Audio.keyFor(searchWords[i]);
                key = key.replace("\\", "\\\\");
                key = key.replace("%", "\\%");
                key = key.replace("_", "\\_");
                keywords[i] = '%' + key + '%';
            }
            for (int i = 0; i < searchWords.length; i++) {
                where.append(" AND ");
                where.append(MediaStore.Audio.Media.ARTIST_KEY + " LIKE ? ESCAPE '\\'");
            }
        }

        String whereclause = where.toString();
        String[] cols = new String[] {
                MediaStore.Audio.Artists._ID, MediaStore.Audio.Artists.ARTIST,
                MediaStore.Audio.Artists.NUMBER_OF_ALBUMS,
                MediaStore.Audio.Artists.NUMBER_OF_TRACKS
        };
        Cursor ret = null;
        if (async != null) {
            async.startQuery(0, null, MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, cols,
                    whereclause, keywords, MediaStore.Audio.Artists.ARTIST_KEY);
        } else {
            ret = query(context, MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, cols, whereclause,
                    keywords, MediaStore.Audio.Artists.ARTIST_KEY);
        }
        return ret;
    }

    public static Cursor getAudioGenres(Context context) {
        String[] cols = new String[] {
                MediaStore.Audio.Genres._ID, MediaStore.Audio.Genres.NAME,

        };
        Cursor ret = null;
        ret = query(context, MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, cols, null, null,
                MediaStore.Audio.Genres._ID);
        return ret;
    }

    public static Cursor query(Context context, Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder, int limit) {
        try {
            ContentResolver resolver = context.getContentResolver();
            if (resolver == null) {
                return null;
            }
            if (limit > 0) {
                uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
            }
            return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
        } catch (UnsupportedOperationException ex) {
            return null;
        }

    }

    public static Cursor query(Context context, Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        return query(context, uri, projection, selection, selectionArgs, sortOrder, 0);
    }

    public Cursor getAlbumCursor(Context context, AsyncQueryHandler async, String filter) {
        StringBuilder where = new StringBuilder();
        where.append(MediaStore.Audio.Albums.ALBUM + " != ''");
        String mArtistId = null;
        // Add in the filtering constraints
        String[] keywords = null;
        if (filter != null) {
            String[] searchWords = filter.split(" ");
            keywords = new String[searchWords.length];
            Collator col = Collator.getInstance();
            col.setStrength(Collator.PRIMARY);
            for (int i = 0; i < searchWords.length; i++) {
                String key = MediaStore.Audio.keyFor(searchWords[i]);
                key = key.replace("\\", "\\\\");
                key = key.replace("%", "\\%");
                key = key.replace("_", "\\_");
                keywords[i] = '%' + key + '%';
            }
            for (int i = 0; i < searchWords.length; i++) {
                where.append(" AND ");
                where.append(MediaStore.Audio.Media.ARTIST_KEY + "||");
                where.append(MediaStore.Audio.Media.ALBUM_KEY + " LIKE ? ESCAPE '\\'");
            }
        }

        String whereclause = where.toString();

        String[] cols = new String[] {
                MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ARTIST,
                MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ALBUM_ART
        };
        Cursor ret = null;
        if (mArtistId != null) {
            if (async != null) {
                async.startQuery(0, null, MediaStore.Audio.Artists.Albums.getContentUri("external",
                        Long.valueOf(mArtistId)), cols, whereclause, keywords,
                        MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
            } else {
                ret = query(context, MediaStore.Audio.Artists.Albums.getContentUri("external", Long
                        .valueOf(mArtistId)), cols, whereclause, keywords,
                        MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
            }
        } else {
            if (async != null) {
                async.startQuery(0, null, MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, cols,
                        whereclause, keywords, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
            } else {

                ret = MusicOperate.query(context, MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                        cols, whereclause, keywords, MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);
            }
        }
        return ret;
    }

}
